import 'dart:typed_data';
import 'package:flutter/services.dart';

class MethodChannelManager {
  factory MethodChannelManager() => _getInstance();

  static MethodChannelManager get instance => _getInstance();
  static MethodChannelManager _instance;
  MethodChannel channel;
  static final String METHOD_CHANNEL = "com.mx.print/method_channel";
  static final String GET_BLUE_DEVICES = "get_blue_devices";
  static final String OPEN_PRINT = "open_print";
  static final String SEND_STRING = "send_string";
  static final String SEND_QR_STRING = "send_qr_string";
  static final String SEND_BAR_STRING = "send_bar_string";
  static final String SEND_BYTES = "send_bytes";
  static final String CLOSE_PRINT = "close_print";
  static final String PRINT_TEST = "print_test";

  MethodChannelManager._internal() {
    // 初始化
    channel = new MethodChannel(METHOD_CHANNEL);
  }

  static MethodChannelManager _getInstance() {
    if (_instance == null) {
      _instance = new MethodChannelManager._internal();
    }
    return _instance;
  }

  ///获取连接的蓝牙设备
  ///返回获取的蓝牙设备集合
  ///example [{"deviceName":"ear pod","deviceAddress","D3:H4:M7..."}]
  ///蓝牙没有开启，返回null
  ///蓝牙开启，没有连接设备返回长度为0的集合
  Future getBlueDevices() async {
    return await channel.invokeMethod(GET_BLUE_DEVICES);
  }

  ///开启打印流
  ///返回内容格式{"result":true,"msg":"open printer success"}
  ///需要判断 result=true方可进行打印操作，result=false可获取msg内容进行提示
  Future openPrint(String deviceAddress) async {
    return await channel.invokeMethod(OPEN_PRINT, deviceAddress);
  }

  ///发送byte打印数据
  ///listInt 打印的字节
  Future sendBytes(List<int> listInt) async {
    return await channel.invokeMethod(SEND_BYTES, Uint8List.fromList(listInt));
  }

  ///发送String打印数据
  ///string 打印的内容
  Future sendString(String string) async {
    return await channel.invokeMethod(SEND_STRING, string);
  }

  ///发送条形码打印数据
  ///content 条形码内容
  Future sendBarString(String content) async {
    return await channel.invokeMethod(SEND_BAR_STRING, content);
  }

  ///发送二维码打印数据
  ///content 二维码内容
  Future sendQRString(String content) async {
    return await channel.invokeMethod(SEND_QR_STRING, content);
  }

  ///关闭打印流
  Future closePrint() async {
    return await channel.invokeMethod(CLOSE_PRINT);
  }

  ///不发送内容，只发送命令到原生进行打印
  ///address 蓝牙设备MAC地址
  Future test(String address) async {
    channel.invokeMethod(PRINT_TEST, address);
  }

  ///监听扫描的回调
  void setMethodCallHandler({Function onScan}) {
    Future<dynamic> platformCallHandler(MethodCall call) async {
      switch (call.method) {
        case "device_scan":
          if (onScan != null) onScan(call.arguments);
          break;
      }
    }

    channel.setMethodCallHandler(platformCallHandler);
  }
}
